//@flow

import { Record } from 'immutable'

import { REHYDRATE } from 'redux-persist/constants'

import { handleActions } from 'redux-actions'

import { setContent, setUserInfo, removeToken, updateToken } from './TokenActions'

export const TokenRecord = Record({
    content: null,     //登录成功返回的token值，用于调除登录、获取验证码外调接口
    userInfo: null,    //登录成功后再调用获取用户信息调接口
    wattingRestore: true,   //等待恢复
    isRestore: false,       //是否恢复
}, 'TokenRecord');

export default function (state, action) {
    if(!state) {
        return new TokenRecord({wattingRestore: true})
    }
    if(action.type === REHYDRATE) {
        //刷新页面时redux-persist会dispatch REHYDRATE action 动作，在此时做数据恢复操作
        var incoming = action.payload.tokenReducer;
        if (incoming) return new TokenRecord({
            content: incoming.content,
            userInfo: incoming.userInfo,
            isRestore: true,
            wattingRestore:false,
        })
        return state
            .set('isRestore', false)
            .set('wattingRestore', false)
    }
    return reducer(state, action)
}

const reducer = handleActions(
    {
        [setContent]: (state, action) => {
            return new TokenRecord({
                content: action.payload,
                userInfo: null,
                wattingRestore: false,
                isRestore: false,
            })
        },
        [setUserInfo]: (state, action) => {
            return new TokenRecord({
                content: action.payload.content,
                userInfo: action.payload.userInfo,
                wattingRestore: false,
                isRestore: false,
            })
        },
        [removeToken]: (state, action) => {
            return new TokenRecord({wattingRestore: false})
        },
        [updateToken]: (state, action) => {
            return state.set('content', action.payload)
        },
    },
    {}
  );